package cn.lingyangwl.agile.auth.listener;

import cn.lingyangwl.agile.auth.model.mq.*;
import cn.lingyangwl.agile.auth.service.*;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author shenguangyang
 */
@Slf4j
@Component
@RabbitListener(bindings = {
        @QueueBinding(
                value = @Queue(value = LoginLogMQ.QUEUE, durable = "true"),
                exchange = @Exchange(value = LoginLogMQ.EXCHANGE, type = ExchangeTypes.TOPIC))
})
public class LoginLogListener {
    @Resource
    private AuthLoginLogService loginLogService;

    @RabbitHandler
    public void onMessage(@Payload String msg, Channel channel, Message message) {
        try {
            LoginLogMQ.MsgPayload payload = LoginLogMQ.parse(msg, LoginLogMQ.MsgPayload.class);
            log.info("save login log: {}", msg);
            loginLogService.save(payload);
        } catch (Exception e) {
            log.error("error: ", e);

        }
    }
}
